package net.ycxinxing.mcpebox.ui;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TextInputEditText;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.text.InputType;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.io.File;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import net.ycxinxing.mcpebox.CallbackBundle;
import net.ycxinxing.mcpebox.Pro.R;
import net.ycxinxing.mcpebox.baseActivity;
import net.ycxinxing.mcpebox.mDialog;
import net.ycxinxing.mcpebox.mObject;
import net.ycxinxing.mcpebox.ui.InstallActivity;
import net.ycxinxing.mcpebox.utils.OpenFileDlg;
import net.ycxinxing.mcpebox.utils.Utils;

public class InstallActivity extends baseActivity
{
	private ListView list;
	private SwipeRefreshLayout layout;
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// TODO: Implement this method
		super.onCreate(savedInstanceState);
		setContentView(R.layout.view_fabactivity);
		list = (ListView)findViewById(R.id.viewfabactivityListView1);
		((FloatingActionButton)findViewById(R.id.viewfabactivityFloatingActionButton1)).setOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View p1)
				{
					showDialog(0);
					// TODO: Implement this method
				}
			});
		layout = (SwipeRefreshLayout)findViewById(R.id.viewfabactivitySwipeRefreshLayout1);
		list.setOnItemClickListener(new OnItemClickListener(){
				@Override
				public void onItemClick(AdapterView<?> p1, View p2, final int p3, long p4)
				{
					mDialog dlg=new mDialog(InstallActivity.this){
						@Override
						public void onButtonClick(int id)
						{
							final List<File> arr=new ArrayList<File>();
							File[] files=new File("/data/data/" + getPackageName() + "/jnitmp/").listFiles();
							for (int i=0;i < files.length;i++)
							{
								if (files[i].isDirectory())
								{
									arr.add(files[i]);
								}
							}
							switch (id)
							{
								case 0:
									Utils.deleteFile(arr.get(p3));
									refish();
									break;
								case 1:
									final TextInputEditText et=new TextInputEditText(InstallActivity.this);
									mDialog dlg=new mDialog(InstallActivity.this){
										@Override
										public void onButtonClick(int i)
										{
											File dest=new File(arr.get(p3).getParent() + "/v" + et.getText().toString() + "/");
											arr.get(p3).renameTo(dest);
											refish();
											// TODO: Implement this method
										}
									};
									dlg.setTitle("新名称");
									et.setHint("任何数字");
									et.setInputType(InputType.TYPE_CLASS_NUMBER);
									dlg.setView(et);
									dlg.setButton3("确定");
									dlg.show();
									break;
							}
							// TODO: Implement this method
						}
					};
					dlg.setTitle("选择一项操作");
					List<String> list=new ArrayList<String>();
					list.add("卸载");
					list.add("重命名");
					dlg.setList(list);
					dlg.show();

					// TODO: Implement this method
				}
			});
		layout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener(){
				@Override
				public void onRefresh()
				{
					refish();
					// TODO: Implement this method
				}
			});
		refish();
	}
	public void refish()
	{
		layout.setRefreshing(true);
		new Handler().postDelayed(new Runnable(){

				@Override
				public void run()
				{
					// TODO: Implement this method
					List<String> arr=new ArrayList<String>();
					if (!new File("/data/data/" + getPackageName() + "/jnitmp/").exists())
					{
						new File("/data/data/" + getPackageName() + "/jnitmp/").mkdirs();
					}
					File[] files=new File("/data/data/" + getPackageName() + "/jnitmp/").listFiles();
					for (int i=0;i < files.length;i++)
					{
						if (files[i].isDirectory())
						{
							arr.add(files[i].getName());
						}
					}
					ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(InstallActivity.this, android.R.layout.simple_spinner_item, arr);
					list.setAdapter(arrayAdapter);
					layout.setRefreshing(false);
				}
			}, 700);
	}
	@Override
	protected Dialog onCreateDialog(int id, Bundle args)
	{
		if (id == 0)

		{
			Map<String, Integer> images = new HashMap<String, Integer>();
			// 下面几句设置各文件类型的图标， 需要你先把图标添加到资源文件夹
			images.put(OpenFileDlg.sRoot, R.drawable.fi_dir);	// 根目录图标
			images.put(OpenFileDlg.sParent, R.drawable.fi_dir);	//返回上一层的图标
			images.put(OpenFileDlg.sFolder, R.drawable.fi_dir);	//文件夹图标
			images.put("apk", R.drawable.fi_file);	//文件图标
			images.put(OpenFileDlg.sEmpty, R.drawable.fi_file);
			Dialog dialog = OpenFileDlg.createDialog(0, this, "打开文件", new CallbackBundle() {
					@Override
					public void callback(Bundle bundle)
					{
						try
						{
							final String filepath = bundle.getString("path");
							String[] arr=null;
							boolean[] check=null;
							final mObject inmain=new mObject(true);
							if (!new File(filepath).getParentFile().getCanonicalPath().equals(new File("/sdcard/ycxinxing/mcpebox/var/").getCanonicalPath()))
							{
								arr = new String[]{"jni支持库(必选)","主程序"};
								check = new boolean[]{true,true};
							}
							else
							{
								arr = new String[]{"jni支持库(必选)"};
								inmain.setData(false);
								check = new boolean[]{true};
							}
							new AlertDialog.Builder(InstallActivity.this).setMultiChoiceItems(arr,check, new DialogInterface.OnMultiChoiceClickListener(){

									@Override
									public void onClick(DialogInterface p1, int p2, boolean p3)
									{
										if(p2==1)
										{
											inmain.setData(p3);
										}
										// TODO: Implement this method
									}
								}).setTitle("选择待安装的模块").setPositiveButton("下一步", new DialogInterface.OnClickListener(){
									@Override
									public void onClick(DialogInterface p1, int p2)
									{
										final TextInputEditText tv=new TextInputEditText(InstallActivity.this);
										tv.setHint("自定义数字");
										tv.setInputType(InputType.TYPE_CLASS_NUMBER);
										AlertDialog.Builder ab=new AlertDialog.Builder(InstallActivity.this).setTitle("输入您安装的组建的版本号").setView(tv);
										ab.setPositiveButton("安装", new DialogInterface.OnClickListener(){
												@Override
												public void onClick(DialogInterface p1, int p2)
												{
													try
													{
														if((boolean)inmain.getData())
														{
															Utils.copyFile(new File(filepath),new File(new File("/sdcard/ycxinxing/mcpebox/var/").getCanonicalPath()+"/v"+tv.getText().toString()+".apk"));
														}
														boolean flag=true;
														if (new File(filepath).getParentFile().getCanonicalPath().equals(new File("/sdcard/ycxinxing/mcpebox/var/").getCanonicalPath()))
														{
															flag = false;
														}
														in(filepath, "v" + tv.getText(), flag);
													}
													catch (Exception e)
													{
														mDialog dlg=new mDialog(InstallActivity.this){
															@Override
															public void onButtonClick(int i)
															{
																// TODO: Implement this method
															}
														};
														dlg.setTitle("发生错误");
														dlg.setMsg(e.toString());
														dlg.show();
														refish();
													}
													// TODO: Implement this method
												}
											});
										ab.show();
										// TODO: Implement this method
									}
								}).show();
						}
						catch (final Exception e)
						{
							mDialog dlg=new mDialog(InstallActivity.this){
								@Override
								public void onButtonClick(int i)
								{
									// TODO: Implement this method
								}
							};
							dlg.setTitle("发生错误");
							dlg.setMsg(e.toString());
							dlg.show();
							refish();
						}
					}
				}, 
				".apk;",
				images);
			return dialog;
		}
		// TODO: Implement this method
		return super.onCreateDialog(id, args);
	}
	private void in(final String apkpath, final String name, boolean flag) throws Exception
	{
		final ProgressDialog pdg=new ProgressDialog(this);
		pdg.setTitle("请稍后");
		pdg.setCancelable(false);
		pdg.setMessage("我们正在安装...");
		pdg.show();
		try
		{
			final ZipFile file=new ZipFile(apkpath);
			final List<String> abis=new ArrayList<String>();
			Enumeration<? extends ZipEntry> e = file.entries();
			boolean haslib=false;
			while (e.hasMoreElements())
			{
				ZipEntry ae=e.nextElement();
				if (ae.getName().startsWith("lib/"))
				{
					haslib = true;
					String abi=ae.getName().split("/")[1];
					boolean hasabi=false;
					for (int v=0;v < abis.size();v++)
					{
						if (abis.get(v).equals(abi))
						{
							hasabi = true;
						}
					}
					if (!hasabi)
					{
						abis.add(abi);
					}
					//System.out.println(ae.getName());
				}
			}
			if (!haslib)
			{
				throw new RuntimeException("There are no mcpe native library in " + apkpath);
			}
			else
			{
				// TODO: Implement this method
				mDialog dlg=new mDialog(InstallActivity.this){
					@Override
					public void onButtonClick(final int i)
					{
						new Thread(){
							public void run()
							{
								try
								{
									Enumeration<? extends ZipEntry> ea = file.entries();
									boolean hasmcpe=false;
									while (ea.hasMoreElements())
									{
										ZipEntry ae=ea.nextElement();
										if (ae.getName().startsWith("lib/" + abis.get(i) + "/"))
										{
											File f=new File("/data/data/" + InstallActivity.this.getPackageName() + "/jnitmp/" + name + "/" + ae.getName().split("/")[2]);
											hasmcpe = true;
											Utils.writeToFile(file.getInputStream(ae), f);
										}
									}
									InstallActivity.this.runOnUiThread(new Runnable(){
											@Override
											public void run()
											{
												// TODO: Implement this method
												pdg.dismiss();
												refish();
											}});
								}
								catch (final Exception e)
								{
									InstallActivity.this.runOnUiThread(new Runnable(){
											@Override
											public void run()
											{
												// TODO: Implement this method

												mDialog dlg=new mDialog(InstallActivity.this){
													@Override
													public void onButtonClick(int i)
													{
														// TODO: Implement this method
													}
												};
												dlg.setTitle("发生错误");
												dlg.setMsg(e.toString());
												dlg.show();
												refish();
												pdg.dismiss();
											}});
								}
							}
						}.start();
						// TODO: Implement this method
					};
				};
				dlg.setList(abis);
				dlg.setCanClose(false);
				dlg.setTitle("选择一个最适合您机器的架构，选择错误会导致无法启动!");
				dlg.show();
			}
		}
		catch (final Exception e)
		{
			mDialog dlg=new mDialog(InstallActivity.this){
				@Override
				public void onButtonClick(int i)
				{
					// TODO: Implement this method
				}
			};
			dlg.setTitle("发生错误");
			dlg.setMsg(e.toString());
			dlg.show();
			refish();
			pdg.dismiss();
			// TODO: Implement this method
		}

	}
}
